$(function(){
	validateInit();
	dataInit();
});


function validateInit() {
	
	jQuery.validator.addMethod("provinceRequired", function(value, element) {
		var province = $("#submitAddressForm [name='province']").val();
		if (province == '---- 选择省 ----' || province == '' || province == null) {
			return false;
		}
		return true;
	}, "请选择省份");
	jQuery.validator.addMethod("cityRequired", function(value, element) {
		var city = $("#submitAddressForm [name='city']").val();
		if (city == '---- 选择市 ----' || city == '' || city == null) {
			return false;
		}
		return true;
	}, "请选择城市");
	jQuery.validator.addMethod("districtRequired", function(value, element) {
		var district = $("#submitAddressForm [name='district']").val();
		if (district == '---- 选择区 ----' || district == '' || district == null) {
			return false;
		}
		return true;
	}, "请选择区地址");
	    
    $("#submitAddressForm").validate({                   
        rules:{
        	province: {
        		provinceRequired: true
        	},
        	city: {
        		cityRequired: true
        	},
        	district: {
        		districtRequired: true
        	},
        	billAddressDetail:{
                required: true,
                minlength: 5,
                maxlength: 500
            }
        },
        
        // Messages for form validation
        messages:{
        },                  
        
        success : function(label, element) {// error是lavel标签，element是input标签
			validSuccess(element,label);
		},
		errorPlacement : function(label, element) {
			validError(element,label);
		}
    });
    $("#assessForm").validate({                   
        rules:{
        	billAssess:{
                required: true,
                minlength: 5,
                maxlength: 500
            }
        },
        
        // Messages for form validation
        messages:{
        },                  
        
        success : function(label, element) {// error是lavel标签，element是input标签
			validSuccess(element,label);
		},
		errorPlacement : function(label, element) {
			validError(element,label);
		}
    });
}

function dataInit() {
	//报修记录
	$.ajax({
		url: "../bill/queryProcess.action",
		type: "post",
		success: function(data) {
			
			var processInfo =   '<div class="d-md-flex justify-content-between g-mb-30">'
							+		'<h3 class="h6 text-uppercase g-mb-10 g-mb--lg">共有 <span class="g-color-gray-dark-v1">'+data.length+'</span> 条报修记录</h3>'
							+	'</div>';
			if (data.length == 0) {
				$("#processInfo").html(processInfo);
				return;
			}
			data = data.reverse();
			$(data).each(function(index, obj){
				var contract = getContractById(obj.contractId);
				var device = getDeviceById(contract.deviceId);
				processInfo+=	'<article>'
							+		'<header class="g-mb-15">'
							+			'<h2 class="h4 g-mb-5">'
							+				'<a class="u-link-v5 g-color-gray-dark-v1 g-color-primary--hover" href="#">'+device.deviceName+'</a>'
							+			'</h2>'
							+			'<span class="g-color-primary">当前状态:'+getBillStatus(obj.billStatus)+'</span>'
							+		'</header>'
							+		'<p class="g-mb-15">';
				$.ajax({
					url: "../billLog/query.action",
					type: "post",
					data: {"billId": obj.id},
					async: false,
					success: function(data) {
						$(data).each(function(){
							var operateUserName = '';
							if (this.operateUserType == '2') {
								operateUserName = getUserNameById(this.operateUserId);
							} else if (this.operateUserType == '1') {
								var cus = getCustomerById(this.operateUserId);
								operateUserName = cus.customerName;
							}
							processInfo += "操作人："+operateUserName+"&nbsp;&nbsp;&nbsp;&nbsp; 操作事件："+this.operateEvent+"&nbsp;&nbsp;&nbsp;&nbsp; 操作时间："+moment(this.operateTime).format('YYYY-MM-DD HH:mm:ss')+"<br/>";
							if (this.operateEvent == '提交维修地址') {
								processInfo += "维修地址：" + obj.billAddress + "<br/>";
							}
							if (this.operateEvent == '报修评价') {
								processInfo += "评价内容：" + obj.billAssess + "<br/>";
							}
						});
					},
					error: function() {
						toastr.error("获取报修操作记录发生错误，请稍后尝试");
					}
				});
				var operateBtn = '';
				if(obj. billStatus == '2') {
					//待提交地址
					operateBtn = '<button onclick="submitAddress('+obj.id+')" class="btn-u btn-u-blue btn-u">提交地址</button>'
				} else if (obj.billStatus == '5') {
					//待评价
					operateBtn = '<button onclick="assess('+obj.id+')" class="btn-u btn-u-blue btn-u">评价</button>'
				}
				processInfo +=		'</p>'
							+		'<div class="d-lg-flex justify-content-between align-items-center">'
							+			'<ul class="list-inline g-mb-10 g-mb-0--lg">'
							+				'<li class="list-inline-item g-mr-30">'
							+					operateBtn
							+				'</li>'
							+			'</ul>'
							+			'<div>'
							+				'<span class="js-rating g-color-primary mr-2" data-rating="5"></span>'
							+				'<span class="g-color-gray-dark-v5">报修时间：'+ moment(obj.createTime).fromNow()+'</span>'
							+			'</div>'
							+		'</div>'
							+	'</article>'
							+	'<hr class="g-brd-gray-light-v4 g-my-40">';


				$("#processInfo").html(processInfo);
			});
		},
		error: function() {
			toastr.error("获取报修信息发生错误，请稍后尝试");
		}
	});
  
}

	
function getBillStatus(status) {
	if (status == '0') {
		return "审核拒绝"
	} else if (status == '1') {
		return "待审核";
	} else if (status == '2') {
		return "审核通过，待提交维修地址";
	} else if (status == '3') {
		return "维修地址已提交，待维修师抢单";
	} else if (status == '4') {
		return "维修师已抢单，待维修";
	} else if (status == '5') {
		return "维修已完成，待评价";
	} else if (status == '6') {
		return "客户评价完成";
	}
}


function submitAddress(billId) {
	formReset("#submitAddressForm")
	$("#submitAddressForm [name='id']").val(billId);
	$("#submitAddressModal").modal("show");
}
function assess(billId) {
	formReset("#assessForm")
	$("#assessForm [name='id']").val(billId);
	$("#assessModal").modal("show");
}

function submitAddressSave() {
	if (!$("#submitAddressForm").valid()) {
		return;
	}
	var id = $("#submitAddressForm [name='id']").val();
	var province = $("#submitAddressForm [name='province']").val();
	var city = $("#submitAddressForm [name='city']").val();
	var district = $("#submitAddressForm [name='district']").val();
	var billAddressDetail = $("#submitAddressForm [name='billAddressDetail']").val();
	var billAddress = province + city +district + billAddressDetail;
	//console.log(id + '----' + billAddress);
	$.ajax({
		url: "../bill/submitAddress.action",
		type: "post",
		data: {"id":id, "billAddress": billAddress},
		success: function(data) {
			if (data.success == "true") {
				//银盆岭含光路412号东50米公寓
				toastr.success("维修地址提交成功");
				dataInit();
			} else {
				toastr.error("后台处理发生错误，请稍后尝试");
			}
		},
		error: function () {
			toastr.error("提交请求发生错误，请稍后尝试");
		}
	});
	
	$("#submitAddressModal").modal("hide");
}

function assessSave() {
	if (!$("#assessForm").valid()) {
		return;
	}
	var data = $("#assessForm").serialize();
	console.log(data);
	$.ajax({
		url: "../bill/update.action",
		type: "post",
		data: data,
		success: function(data) {
			if (data.success == "true") {
				toastr.success("报修评价提交成功");
				dataInit();
			} else {
				toastr.error("后台处理发生错误，请稍后尝试");
			}
		},
		error: function () {
			toastr.error("提交请求发生错误，请稍后尝试");
		}
	});
	
	$("#assessModal").modal("hide");
}
